package com.wsz.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsz.security.pojo.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        Map<String,Object> data = new HashMap<>();
        data.put("msg:","登陆失败");
        data.put("status:",201);
        data.put("异常信息:", e);
        String s = new ObjectMapper().writeValueAsString(data);
        httpServletResponse.getWriter().println(s);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        Map<String,Object> data = new HashMap<>();
        data.put("msg:","登陆成功");
        data.put("status:",200);
        data.put("用户信息:",(User) authentication.getPrincipal());
        String s = new ObjectMapper().writeValueAsString(data);
        httpServletResponse.getWriter().println(s);
    }

}
